<?php
namespace app\front\controller;
use think\facade\Db;

use app\front\logic\ApiLogic;
use app\front\logic\EmailLogic;
use app\common\logic\MemberAccountLogic;
use app\common\logic\EmailOrderLogic;

class Email extends Base{
    function getList(){
    	$data = EmailLogic::init()->getList($this->lang, $this->exchange_rate);
    	return ApiLogic::return($this->lang, 0, '', $data);
    }

    //购买邮箱
    function buyEmail(){
    	if(!$this->member_info || !$this->member_info['id']){
    		return ApiLogic::return($this->lang, $this->has_login);
    	}
        //开启事务
        Db::startTrans();
        try {
            //生成订单
            $total_amount = $this->total_amount * $this->exchange_rate;
            $rs = EmailLogic::init()->buyEmail($this->lang, $this->member_info['id'], $total_amount);
            if($rs['code']!=0){
                Db::rollback();
                return ApiLogic::return($this->lang, $rs['code']);
            }
            //订单生成成功，开始扣款
            $rs2 = MemberAccountLogic::init()->accountOut($rs['data']['email_sn'], 2);
        	if(!$rs2){
                Db::rollback();
                return ApiLogic::return($this->lang, 141);
            }
            //订单付款成功，修改订单状态
            $rs3 = EmailOrderLogic::init()->orderProcess($rs['data'], 20);
            if(!$rs3){
                Db::rollback();
                return ApiLogic::return($this->lang, 141);
            }
            Db::commit();
        } catch (\Exception $e) {
            // print_r($e->getMessage());
            // 回滚事务
            Db::rollback();
            return ApiLogic::return($this->lang, 141);
        }

        return ApiLogic::return($this->lang, 0, '购买成功', ['email_sn'=>$rs['data']['email_sn'],'mdfkey'=>$rs['data']['mdfkey']]);

    }

    //获取购买的邮箱订单
    function getOrderList(){
        if(!$this->member_info || !$this->member_info['id']){
            return ApiLogic::return($this->lang, $this->has_login);
        }
        $data = EmailLogic::init()->getOrderList($this->lang, $this->member_id, $this->exchange_rate);
        return ApiLogic::return($this->lang, 0, '', $data);
    }

    

}
